<!--
 * @Description: * 登录页
 * @Date: 2020-08-26 16:24:02
 * @LastEditTime: 2020-08-27 00:56:42
 * @Author: SBD
 * @FilePath: /cms/src/views/Login/login.vue
-->
<template>
  <div class="login_">
    <div>
      <el-input v-model="user" placeholder="请输入账号"></el-input>
      <el-input placeholder="请输入密码" v-model="pass" show-password></el-input>
      <el-button type="primary" :loading="loading" @click.native="sub">登录</el-button>
      <p>this.$store.state.name: {{this.$store.state.name}}</p>
      <p>name: {{ name }}</p>
      <p>getName: {{ getName }}</p>
      <el-button type="primary" :loading="loading" @click.native="alterName('joe')">vuex</el-button>
      <p>{{userName}}</p>
      <p>{{getUserName}}</p>
      <el-button type="primary" :loading="loading" @click.native="alterUserName('韩梅梅')">vuex-modules</el-button>
    </div>
  </div>
</template>
<script>
/*
    mapState, mapGetters, mapActions, mapMutations
    这些名字呢，是对应四大金刚的一个辅助函数，
*/
import { mapState,mapGetters,mapMutations } from 'vuex'
export default {
  name: "login_",
  components: {},
  data() {
    return {
      user: "admin",
      pass: "888888",
      loading: false,
    };
  },
  computed: {
      ...mapState(['name']), // 等价1、 this.$store.state.name || 等价2、 ...mapState({name_: 'name'})
      ...mapGetters(['getName']), // this.$store.getters.getName
      /* 模块化vuex */   
      ...mapState("user",["userName"]),
      ...mapGetters("user",['getUserName']),
  },
  mounted: function () {

      console.log({...mapState(['name'])});
  },
  methods: {
    ...mapMutations(['alterName']), // this.$store.commit("alterName",'joe')
    /* 模块化vuex */ 
    ...mapMutations("user",['alterUserName']),
    /* 登录操作 */
    sub() {
      if (this.user !== "admin" || this.pass !== "888888") {
        this.$message.error("错了哦，账号或密码错误！");
        return;
      }

      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.$router.push("/home");
      }, 1000);

      this.$req({
        method: "POST",
        url: "/home",
        data: {
          account: this.user,
          psw: this.pass,
        },
      }).then(
        (res) => {
          console.log("res :", res);
          localStorage.setItem("hasLogin", true);
          localStorage.setItem("token", res.data.token);
          localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));
          this.$router.push({ path: "/" });
        },
        (err) => {
          console.log("err :", err);
          this.passwordError = true;
          this.loading = false;
        }
      );
    },
  },
};
</script>
<style lang="scss">
.login_ {
  > div {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 400px;
    height: 200px;
    input {
      margin-bottom: 10px;
      margin-top: 10px;
    }
    button {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>